package com.springboot.blog.controller.admin;

import com.springboot.blog.dto.LayResponse;
import com.springboot.blog.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
class AdminLoginController {
    @Autowired
    IUserService userService;
    String PATH = "admin/login/";

    @GetMapping(value = {"/admin/login/index", "/admin/login"})
    public String index() {
        return PATH + "index";
    }

    @PostMapping(value = {"/admin/login"})
    @ResponseBody
    public LayResponse login(@RequestParam Map<String, String> param, HttpServletRequest req) {
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(param.get("username"), param.get("password"));
        LayResponse response = new LayResponse();
        response.success("登录成功");
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
            SavedRequest savedRequest= WebUtils.getSavedRequest(req);//将需要调整的页面传回前段,前段进行跳转
            response.data(savedRequest);
        } catch (UnknownAccountException e) {
            response.error("用户名不存在！");
        } catch (AuthenticationException e) {
            response.error("账号或密码错误！");
        } catch (AuthorizationException e) {
            response.error("没有权限");
        } catch (Exception e) {
            response.error("其他错误");
        }
        return response;
    }
}
